package 力扣日常刷题.木23一月.第08天308;

import 力扣日常刷题.ListNode;

/**
 * @author 帅小伙
 * @date 2022/3/8
 * @description
 */
public class Demo21K个一组翻转链表 {


    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || head.next == null) return head;
        ListNode tail = head;
        for (int i = 0; i < k; i++) {
            // 数量小于看
            if(tail == null) return head;
            tail = tail.next;
        }
        // 反转前k个
        ListNode newHead = reverse(head,tail);
        head.next = reverseKGroup(tail,k);
        return newHead;
    }

    public ListNode reverse(ListNode head,ListNode tail) {
        ListNode pre = null;
        ListNode next = null;

        while(head != tail) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}
